package org.tmsps.ne4spring.utils.api;

import java.util.ArrayList;
import java.util.List;

public class FunctionModel {

	public static final String RequestMapping_MODEL = "@RequestMapping(\"/@function_name\")";
	public static final String RequestParam_MODEL = "@RequestParam(\"@param\")";

	private String functionOriginal;
	private String name;
	private String functionMiddle;
	private List<String> params = new ArrayList<>();
	private String functionEnd;

	public FunctionModel(String functionOriginal) {
		this.functionOriginal = functionOriginal;
		this.makeName();
		this.makeMiddle();
		this.makeParams();
		this.makeFunctionEnd();

	}

	/**
	 * 获取 函数名
	 * 
	 * @return
	 */
	private void makeName() {
		int end = functionOriginal.indexOf("(");
		int start = functionOriginal.lastIndexOf(" ", end) + 1;
		this.name = functionOriginal.substring(start, end);
	}

	/**
	 * 获取中间参数
	 * 
	 * @return
	 */
	private void makeMiddle() {
		int start = functionOriginal.indexOf("(") + 1;
		int end = functionOriginal.indexOf(")");
		this.functionMiddle = functionOriginal.substring(start, end);
	}

	private void makeParams() {
		String[] middles = this.functionMiddle.split(",");
		for (String mid : middles) {
			mid = mid.trim();
			if (mid.length() > 0 && mid.contains(" ")) {
				if (this.isRequestBody(mid)) {
					params.add("@RequestBody " + mid);
				} else {
					String[] mids = mid.split(" ");
					mid = RequestParam_MODEL.replace("@param", mids[1]) + " " + mid;
					params.add(mid);
				}

			}
		}
	}

	private void makeFunctionEnd() {
		String endMiddle = "";
		if (params.size() == 0) {
			this.functionEnd = this.functionOriginal;
			return;
		}
		for (String p : params) {
			endMiddle += p + ",";
		}
		endMiddle = endMiddle.substring(0, endMiddle.length() - 1);
		this.functionEnd = this.functionOriginal.replace(this.functionMiddle, endMiddle);
	}

	// 是否 RequestBody 类型参数
	private boolean isRequestBody(String mid) {
		if (mid.startsWith("String")) {
			return false;
		}
		if (mid.startsWith("int")) {
			return false;
		}
		return true;
	}

	public String toApi() {
		String api = "";
		api += RequestMapping_MODEL.replace("@function_name", name);
		api += "\n";
		api += this.functionEnd;
		return api;
	}

}
